package com.tskj.leonsu.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.deserializer.JSONPDeserializer;
import com.tskj.leonsu.dao.MealsDAO;
import com.tskj.leonsu.db.redis.redisson.DistributedLocker;
import com.tskj.leonsu.db.redis.util.RedisUtil;
import com.tskj.leonsu.utility.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 餐厅服务类
 *
 * @author LeonSu
 */
@Service
public class RestaurantService {

    @Autowired
    private MealsDAO mealsDAO;

    @Autowired
    private DistributedLocker distributedLocker;

    /**
     * 获取餐厅列表
     *
     * @return
     */
    public JSONArray getRestaurant() {
        return mealsDAO.getRestaurantList();
    }

    public boolean getCanteenStatus() {
        return mealsDAO.getCanteenStatus();
    }
    /**
     * 获取分餐时间段，早餐、中餐、晚餐
     *
     * @return
     */
    public JSONArray getTimeType() {
        return mealsDAO.getTimeTypeList();
    }

    /**
     * 检查学生在当天的指定食堂的指定餐段中有没有下过订单
     * 同一天，同一食堂，同一餐段，只能有一个订单
     * @param adUserName
     * @param resId
     * @param timeTypeId
     * @return
     */
    public Boolean checkOrder(String adUserName, String date, String resId, String timeTypeId) {
        return mealsDAO.checkHasOrder(adUserName, date, resId, timeTypeId);
    }

    /**
     * 获取餐厅下的套餐列表
     *
     * @param restaurantId
     * @return
     */
    public JSONArray getFoodList(String restaurantId, String timeTypeId) {
        JSONArray allList = mealsDAO.getList(restaurantId, timeTypeId);
        JSONArray retList = new JSONArray();
        JSONObject data, json;
        for (Object obj : allList) {
            json = (JSONObject) obj;
            data = new JSONObject();
            data.put("id", json.getString("mid"));
            data.put("title", json.getString("mealname"));
            data.put("desc", json.getString("mdetails"));
            data.put("price", json.getString("money"));
            data.put("img", json.getString("photo"));
            retList.add(data);
        }
        return Tools.jsonArraySort(retList, "title", false);
    }

    public JSONArray getUnFinishedOrder(String adUserName) {
        return mealsDAO.getUnFinishedOrder(adUserName);
    }

    public JSONArray getFinishedOrder(String adUserName) {
        return mealsDAO.getFinishedOrder(adUserName);
    }

    public JSONArray getAllOrder(String adUserName) {
        return mealsDAO.getAllOrder(adUserName);
    }

    public void confirmOrder(String adUserName, String id) throws Exception {
        if (mealsDAO.getCanConfirm(id)) {
            mealsDAO.confirmOrder(adUserName, id);
        } else {
            throw new Exception("订单确认失败，未到允许订单确认时间");
        }
    }

    public void cancelOrder(String adUserName, String id) throws Exception {
        if (mealsDAO.getCanCancel(id)) {
            JSONObject orderInfo = mealsDAO.getOrderInfo(id);
            String startTime = orderInfo.getString("starttime");
            String endTime = orderInfo.getString("endtime");
            String resId = orderInfo.getString("cid");

            String today = Tools.today();

            //TODO：成功取消后，需要将此订单信息释放，redis中此时间的队列要加1，此时间的used要+1，并且修改前要加锁
            String timeId = mealsDAO.getTimeId(today, resId, startTime, endTime);
            String key = "myLock_FoodOrder_" + today + "_" + timeId;

            try {
                boolean isGetLock = distributedLocker.tryLock(key, TimeUnit.SECONDS, 1L, 10L);
                if (!isGetLock) {
                    throw new Exception("订单取消失败，请稍后重试");
                }
                mealsDAO.cancelOrder(adUserName, id);
                mealsDAO.addOrderCount(today, timeId);
            } finally {
//                distributedLocker.unlock(key);
            }
        } else {
            throw new Exception("订单取消失败，超过订单取消时间");
        }
    }

}
